﻿using Api1.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Api1.Service
{

     class BehaviorLogService : BaseService<BehaviorLog>
    {
        private static BehaviorLogService instance;
        /// <summary>
        /// 会员验证进出场  0验证 1验证
        /// </summary>
        public static int member_varify_in_out=-1;
        /// <summary>
        /// 员工验证进出场  0验证 1验证
        /// </summary>
        public static int staff_varify_in_out = -1;
        /// <summary>
        /// 是否开启临时出场
        /// </summary>
        public static int temp_out = -1;
       
        private BehaviorLogService() {

        }
        public static BehaviorLogService GetInstance() {
            if (instance == null)
            {
                instance = new BehaviorLogService();
            }
            return instance;
        }
       /// <summary>
       /// 新增日志
       /// </summary>
       /// <param name="behavior"></param>
       /// <returns>新增的id</returns>
        public  long AddBehaviorLog(BehaviorLog behavior) {
            return Insert(behavior);
        }
        /// <summary>
        /// 是否已经 进出判断
        /// </summary>
        /// <param name="card_no">卡号</param>
        /// <param name="brackmachine_no">闸机编号</param>
        /// <param name="owner_type">用户类型 1会员 2员工</param>
        /// <returns></returns>
        public int IsInOrOutVarify(String card_no,String brackmachine_no,int owner_type) {
            if (GetVarifyInOut(owner_type) == 0)
            {//无需验证
                return 0;
            }
            else {//需要验证
                //最后一次刷卡
                BehaviorLog log = Find(String.Format("select * from m_behavior_log where card_no='{0}' and behavior_type=1 and behavior_status=1  order by id desc", card_no));
               
                if (Convert.ToInt16(brackmachine_no) % 2 == 1)
                {//进场
                    if (log == null)
                    {
                        return 0;
                    }
                    if (String.IsNullOrEmpty(log.Out_Brakemachine_no))
                    {//没有出场
                        return -1;
                    }
                    else
                    {
                        return 0;
                    }
                }
                else {// 出场
                    if (log == null)
                    {
                        return -2;
                    }
                    if (String.IsNullOrEmpty(log.Out_Brakemachine_no))
                    {
                        return 0;
                    }
                    else
                    {//没有进场
                        return -2;
                    }
                }
            }
        }
        /// <summary>
        /// 获取进出场是否验证
        /// </summary>
        public static int GetVarifyInOut(int owner_type) {
            if (owner_type == 2)
            {// 员工
                if (staff_varify_in_out == -1)
                {
                    staff_varify_in_out=ScalarForInt("select pvalue from m_system_set where id=5");
                }
                return staff_varify_in_out;
            }
            else {// 会员或者零时卡
                if (member_varify_in_out == -1)
                {
                    member_varify_in_out= ScalarForInt("select pvalue from m_system_set where id=4");
                }
                return member_varify_in_out;
            }
        }
        /// <summary>
        /// 临时出场配置
        /// </summary>
        /// <returns></returns>
        public static int GetTempOut() {
            if (temp_out == -1) {
                temp_out = ScalarForInt("select pvalue from m_system_set where id=6");
            }
            return temp_out;
        }
        /// <summary>
        /// 新增进场刷卡日志
        /// </summary>
        /// <param name="interfaces"></param>
        /// <param name="flag">1 成功  ，2失败</param>
        /// <param name="error_msg"></param>
        /// <param name="brakemachine_no"></param>
        /// <param name="sub_time">扣次时间</param>
        /// <returns></returns>
        public long AddInBrackmachineBehavior(Interfaces interfaces,int flag,string error_msg,string brakemachine_no,string sub_time=null)
        {
            if(interfaces!=null){
                var behaviorLog = new BehaviorLog
                {
                    Behavior_Type = 1,
                    Behavior_Status = flag,
                    Card_No = interfaces.Card_No,
                    In_Brakemachine_no = brakemachine_no,
                    Name = interfaces.Name,
                    Mobile = interfaces.Mobile,
                    Member_Id = interfaces.Member_Id,
                    Owner_type = interfaces.Owner_Type,
                    In_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Create_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Error_Msg = error_msg,
                    Sub_Time= sub_time
                };
               return   Insert(behaviorLog);
            }
            return 0;
        }
        /// <summary>
        /// 新增进场验证(指纹 或者人脸)日志
        /// </summary>
        /// <param name="interfaces"></param>
        /// <param name="flag">1 成功  ，2失败</param>
        /// <param name="error_msg"></param>
        /// <param name="brakemachine_no"></param>
        /// <returns></returns>
        public long AddVarifyBehavior(Interfaces interfaces, int flag, string error_msg, string brakemachine_no)
        {
            if (interfaces != null)
            {
                var behaviorLog = new BehaviorLog
                {
                    Behavior_Type = 2,
                    Behavior_Status = flag,
                    Card_No = interfaces.Card_No,
                    In_Brakemachine_no = brakemachine_no,
                    Name = interfaces.Name,
                    Mobile = interfaces.Mobile,
                    Member_Id = interfaces.Member_Id,
                    Owner_type = interfaces.Owner_Type,
                    In_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Create_Time= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Error_Msg = error_msg,
        };
                return Insert(behaviorLog);
            }
            return 0;
        }
        /// <summary>
        /// 获取统计信息
        /// </summary>
        /// <returns></returns>
        public int[] GetStatistic(String card_no)
        {
            //本月运动时场
          int times=ScalarForInt(String.Format("SELECT SUM(TIMESTAMPDIFF(MINUTE,in_time,out_time)) from m_behavior_log where card_no='{0}' and behavior_status=1  AND out_time is NOT null and   DATE_FORMAT(in_time,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m');", card_no));
          int count= ScalarForInt(String.Format("select count(DISTINCT(DATE_FORMAT(in_time,'%Y%m%d'))) from m_behavior_log where card_no='{0}' and behavior_status=1  and   DATE_FORMAT(in_time,'%Y%m')=DATE_FORMAT(CURDATE(),'%Y%m');", card_no));
          int[] mySigArray = {times,count};
           return mySigArray;

        }
        /// <summary>
        /// 记录出场纪录
        /// </summary>
        /// <param name="card_no"></param>
        public long AddOutBrackmachineBehavior(string card_no, String brakemachine_no,String type="-1") {
            if (type.Equals("1")) {
                Interfaces interfaces = InterfaceService.GetInstance().FindByCardno(card_no);
                var behaviorLog = new BehaviorLog
                {
                    Behavior_Type = 1,
                    Behavior_Status = 2,
                    Card_No = card_no,
                    Out_Brakemachine_no = brakemachine_no,
                    Out_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Create_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Error_Msg = "物品未取走，请先取走",
                    Name = interfaces.Name,
                    Mobile = interfaces.Mobile,
                    Owner_type = interfaces.Owner_Type,
                    Member_Id = interfaces.Member_Id
                };
                Insert(behaviorLog);
                return 0;
            }
            ///最后一次成功进场的记录
            int max_id = ScalarForInt(String.Format("select IFNULL(max(id),0) as id from m_behavior_log where behavior_status=1 and card_no='{0}' and length(trim(in_time))>5 and length(trim(out_time))>5", card_no));
            BehaviorLog behavior = Find(String.Format("select * from m_behavior_log where card_no='{0}' and id>{1} and behavior_type=1 and behavior_status=1  and (out_time is  null or length(trim(out_time))<5) order by id desc", card_no, max_id));

            if (behavior == null)
            {//没有进场      
             
                Interfaces interfaces = InterfaceService.GetInstance().FindByCardno(card_no);
                var behaviorLog = new BehaviorLog
                {
                    Behavior_Type = 1,
                    Behavior_Status = 1,
                    Card_No = card_no,
                    Out_Brakemachine_no = brakemachine_no,
                    Out_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Create_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Name=interfaces.Name,
                    Mobile= interfaces.Mobile,
                    Owner_type=interfaces.Owner_Type,
                    Member_Id=interfaces.Member_Id
                };
                Insert(behaviorLog);
                return 0;
            }
            else {
                behavior.Out_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                behavior.Out_Brakemachine_no = brakemachine_no;
                Save(behavior);
                return behavior.Id;
            }
        }        
    }
}
